package where2go.sctu.com.zhiyou.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Scroller;

import java.util.Timer;
import java.util.TimerTask;

/**
 * ProjectName: zhiyou
 * PackageName: where2go.sctu.com.zhiyou.view
 * Created by 张某人
 * CreatedTime:on 2018/4/30   11:37
 * Description: 实现图片轮播
 */

public class ImageBarnnerViewGroup extends ViewGroup {

    private int children;
    private int childHeight;
    private int childWidth;

    private int x;//代表第一次按下的位置的横坐标，每一次移动过程中，移动之前的横坐标
    private int index;//代表每张图片的索引

    private Scroller scroller;

    public ImageBarnnerViewGroupListener getBarnnerViewGroupListener() {
        return barnnerViewGroupListener;
    }

    public void setBarnnerViewGroupListener(ImageBarnnerViewGroupListener barnnerViewGroupListener) {
        this.barnnerViewGroupListener = barnnerViewGroupListener;
    }

    private ImageBarnnerViewGroupListener barnnerViewGroupListener;

    private boolean isAuto = true;  //默认开启自动轮播
    private Timer timer = new Timer();
    private TimerTask task;
    private Handler autohandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:  //此时我们需要图片的自动轮播
                    if (++index >= children) {  //说明是最后一张图片,那么从第一张图片重新开始滑动轮播
                        index = 0;
                    }
                    scrollTo(childWidth * index, 0);
                    barnnerViewGroupListener.selectImage(index);
                    break;

            }
        }
    };

    private void startAuto() {
        isAuto = true;
    }

    private void stopAuto() {
        isAuto = false;
    }


    /**
     * 自动轮播  Timer,TimerTask,Handler
     * 抽取出两个方法来控制是否启动自动轮播
     */
    public ImageBarnnerViewGroup(Context context) {

        super(context);

        initObj();
    }


    public ImageBarnnerViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        initObj();
    }

    public ImageBarnnerViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initObj();
    }

    private void initObj() {
        scroller = new Scroller(getContext());

        task = new TimerTask() {
            @Override
            public void run() {
                if (isAuto) {
                    autohandler.sendEmptyMessage(0);
                }
            }
        };

        timer.schedule(task, 500, 2000);

    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (scroller.computeScrollOffset()) {  //判断是否已经滑动完毕
            scrollTo(scroller.getCurrX(), 0);
            invalidate();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        //1.求出子视图的个数
        children = getChildCount();
        if (0 == children) {
            setMeasuredDimension(0, 0);
        } else {
            //2.测量子视图的宽度和高度
            measureChildren(widthMeasureSpec, heightMeasureSpec);

            View view = getChildAt(0); //此时第一个视图绝对是存在的
            childWidth = view.getMeasuredWidth();

            childHeight = view.getMeasuredHeight();
            int width = view.getMeasuredWidth() * children;
            setMeasuredDimension(width, childHeight);

        }
    }
    /**
     * 事件传递过程中的调用方法：需要调用容器的拦截方法
     * 如果返回true，真正处理该事件的方法时ontouchEvent方法
     *
     * @param ev
     * @return
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: //表示用户按下的一瞬间
                stopAuto();
                if (!scroller.isFinished()) {
                    scroller.abortAnimation();
                }
                x = (int) event.getX();
                break;
            case MotionEvent.ACTION_MOVE://表示用顾按下之后屏幕上移动
                int moveX = (int) getScaleX();
                int distance = moveX - x;
                scrollBy(-distance, 0);
                x = moveX;
                break;
            case MotionEvent.ACTION_UP: //抬起
                int scrollX = getScrollX();
                index = (scrollX + childWidth / 2) / childWidth;
                if (index < 0) { //说明此时已经滑动到最左边第一张图片
                    index = 0;
                } else if (index > children - 1) {
                    index = children - 1;
                }
                int dx = index * childWidth - scrollX;
                scroller.startScroll(scrollX, 0, dx, 0);

                postInvalidate();
                barnnerViewGroupListener.selectImage(index);
                startAuto();
                // scrollTo(index*childWidth,0);
                break;
            default:
                break;

        }
        return true; // 表示告诉用户我已井处理好了该事件
    }

    /**
     * 布局
     * changed  代表是ViewGroup位置发生改变时为true，没有改变时为false
     */


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed) {

            int leftmargin = 0;
            for (int i = 0; i < children; i++) {
                View view = getChildAt(i);
                view.layout(leftmargin, 0, leftmargin + childWidth, childHeight);

                leftmargin += childWidth;
            }
        }
    }
    public interface ImageBarnnerViewGroupListener {
        void selectImage(int index);
    }

}
